package cn.migu.music.hangupsms.service;

import cn.migu.music.cljz.common.HttpHolder;
import cn.migu.music.cljz.common.Province;
import cn.migu.music.hangupsms.remote.CompletePhoneCodeFeignClient;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class LocalIdService {
    @Autowired
    private CompletePhoneCodeFeignClient completePhoneCodeFeignClient;

    ThreadLocal<String>                  msisdnHolder = new ThreadLocal<>();

    private String asLocalId(String msisdn) {
        String provinceName = completePhoneCodeFeignClient.getProvinceName(msisdn);
        Province province = Province.valueOfName(provinceName);
        return province == null ? "" : province.getCode();
    }

    public Integer getLocalId(String msisdn) {
        String localId = this.getLocalIdStr(msisdn);
        return localId == null ? null : Integer.parseInt(localId);
    }

    public Integer getLocalIdForHangUpBlackUser(String msisdn) {
        String localId = this.getLocalIdStr(msisdn);
        return localId == null ? 0 : Integer.parseInt(localId);
    }

    public String getLocalIdStr(String msisdn) {
        String localId = HttpHolder.getLocalId();
        if (StringUtils.isBlank(localId) || !StringUtils.equals(msisdn, msisdnHolder.get())) {
            localId = asLocalId(msisdn);
            if (StringUtils.isBlank(localId)) {
                return null;
            }

            msisdnHolder.set(msisdn);
            HttpHolder.setLocalId(localId);
        }

        return localId;
    }
}
